const { getNohostConfig, setNohostConfig } = require('./context');

/**
 * NoHost 插件管理器
 * 负责管理 NoHost 插件的配置和规则
 */
class NoHostManager {
  constructor() {
    this.config = getNohostConfig() || {};
    this.rules = [];
  }

  /**
   * 设置 NoHost 配置
   * @param {Object} config - 配置对象
   */
  setConfig(config) {
    this.config = { ...this.config, ...config };
    setNohostConfig(this.config);
  }

  /**
   * 获取 NoHost 配置
   * @returns {Object} 配置对象
   */
  getConfig() {
    return this.config;
  }

  /**
   * 添加环境规则
   * @param {string} environment - 环境名称
   * @param {Array} rules - 规则数组
   */
  addEnvironmentRules(environment, rules) {
    if (!this.rules[environment]) {
      this.rules[environment] = [];
    }
    this.rules[environment].push(...rules);
  }

  /**
   * 获取当前激活环境的规则
   * @param {string} environment - 环境名称
   * @returns {Array} 规则数组
   */
  getActiveRules(environment) {
    return this.rules[environment] || [];
  }

  /**
   * 生成 whistle 规则文本
   * @param {string} environment - 环境名称
   * @returns {string} 规则文本
   */
  generateRulesText(environment) {
    const rules = this.getActiveRules(environment);
    if (!rules.length) {
      return '# NoHost Plugin - No active rules\n';
    }

    const rulesText = rules.map(rule => {
      if (typeof rule === 'string') {
        return rule;
      }
      if (rule.domain && rule.proxy) {
        return `${rule.domain} ${rule.proxy}`;
      }
      return '';
    }).filter(Boolean).join('\n');

    return `# NoHost Plugin - ${environment} Environment\n${rulesText}\n`;
  }

  /**
   * 切换环境
   * @param {string} environment - 目标环境名称
   */
  switchEnvironment(environment) {
    if (this.rules[environment]) {
      this.config.activeEnvironment = environment;
      this.setConfig(this.config);
      return true;
    }
    return false;
  }

  /**
   * 获取所有可用环境
   * @returns {Array} 环境名称数组
   */
  getAvailableEnvironments() {
    return Object.keys(this.rules);
  }

  /**
   * 获取当前激活环境
   * @returns {string} 当前激活的环境名称
   */
  getActiveEnvironment() {
    return this.config.activeEnvironment || 'default';
  }
}

// 创建单例实例
const nohostManager = new NoHostManager();

module.exports = nohostManager;
